package com.zlr.hiring.common.util;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.zlr.hiring.company.entity.CompanyEntity;
import com.zlr.hiring.talent.entity.TalentEntity;

/**
 * 当前项目的工具方法
 *
 * @author Hsu.
 * @since 2016年1月19日
 */
public class AppUtil {

	private static Logger LOG = Logger.getLogger(AppUtil.class);

	private AppUtil() {

	}

	/**
	 * 判断Talent是否有登录
	 * 
	 * @param request
	 * @return
	 */
	public static boolean isLogin(HttpServletRequest request) {
		if (request.getSession().getAttribute("talent") == null) {
			return false;
		}
		return true;
	}

	/**
	 * 获取放到Session里面的Talent对象
	 * 
	 * @param request
	 * @return
	 */
	public static TalentEntity getTalent(HttpServletRequest request,
			HttpServletResponse response) {
		if (request.getSession().getAttribute("talent") == null) {
			request.setAttribute("sessionClosed", "会话已经关闭！");
			try {
				request.getRequestDispatcher("view/talent/talent-login.jsp")
						.forward(request, response);
			} catch (ServletException | IOException e) {
				Util.e(LOG, e.getMessage(), e);
			}
			throw new RuntimeException("会话已经关闭！获取Session中的内容失败");
		} else {
			return (TalentEntity) request.getSession().getAttribute("talent");
		}
	}

	/**
	 * 获取放到Session里面的Talent的id
	 * 
	 * @param request
	 * @return
	 */
	public static int getTalentId(HttpServletRequest request,
			HttpServletResponse response) {
		return getTalent(request, response).getId();
	}

	/**
	 * 获取放到Session里面的Company对象
	 * 
	 * @param request
	 * @return
	 */
	public static CompanyEntity getCompany(HttpServletRequest request,
			HttpServletResponse response) {
		if (request.getSession().getAttribute("company") == null) {
			request.setAttribute("sessionClosed", "会话已经关闭！");
			try {
				request.getRequestDispatcher("view/company/company-login.jsp")
						.forward(request, response);
			} catch (ServletException | IOException e) {
				Util.e(LOG, e.getMessage(), e);
			}
			throw new RuntimeException("会话已经关闭！获取Session中的内容失败");
		} else {
			return (CompanyEntity) request.getSession().getAttribute("company");
		}
	}

	/**
	 * 获取放到Session里面的Company的id
	 * 
	 * @param request
	 * @return
	 */
	public static int getCompanyId(HttpServletRequest request,
			HttpServletResponse response) {
		return getCompany(request, response).getId();
	}
}
